<template>
  <a-card
    :bordered="false"
    class="card-area"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form" :id="id">
      <a-form-item label='名称' v-bind="formItemLayout">
        <a-input v-decorator="['name',
                   {rules: [
                    { required: true, message: '名称不能为空'},
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='编号' v-bind="formItemLayout">
        <a-input v-decorator="['code']" style="width: 100%"/>
      </a-form-item>
      <a-form-item label='排序' v-bind="formItemLayout">
        <a-input-number v-decorator="['sort']" style="width: 100%"/>
      </a-form-item>
      <a-form-item label='类型'
                   style="margin-bottom: 2rem"
                   v-bind="formItemLayout">
        <a-tree
          :autoExpandParent="autoExpandParent"
          :parentId="parentId"
          :key="cateTreeKeys"
          :checkable="true"
          :checkStrictly="true"
          v-model="checkedKeys"
          @expand="handleExpand"
          :expandedKeys="expandedKeys"
          :defaultCheckedKeys="defaultCheckedKeys"
          :treeData="cateTreeData">
        </a-tree>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <div style="width: 50%">
        <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
        <a-button @click="onClose" type="primary" :loading="loading">取消</a-button>
      </div>
    </div>
  </a-card>
</template>
<script>
const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18}
}
export default {
  name: 'CategoryEdit',
  data () {
    return {
      childrenId: [],
      selectedId: '',
      autoExpandParent: true,
      id: '',
      parentId: '',
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      cateTreeKeys: +new Date(),
      checkedKeys: [],
      expandedKeys: [],
      defaultCheckedKeys: [],
      cateTreeData: []
    }
  },
  watch: {
    checkedKeys (checkedKeys) {
      console.log(checkedKeys.checked)
      this.$api.goods.findCategory(checkedKeys.checked).then((r) => {
        let data = r.data.data
        this.childrenId = data.childrenId
        console.log(this.childrenId)
      })
    },
    expandedKeys (val, info) {
      console.log('onCheck', val) // 没有key或title
      console.log(info)
    }
  },
  created () {
    const bind = arr => data => arr.reduce((r1, r2) => {
      r1[r2] = this.$form.createFormField({
        value: data[r2]
      })
      return r1
    }, {})
    this.$api.goods.findCategory(this.$route.query.id).then((r) => {
      // console.info("獲得修改后數據：",r)
      let data = r.data.data
      this.id = data.id
      console.log(this.id)
      this.checkedKeys.push(this.id)
      console.log(this.checkedKeys)
      this.parentId = data.parentId
      this.expandedKeys.push(this.parentId)
      this.form = this.$form.createForm(this, {
        mapPropsToFields: () => {
          return bind(['name', 'code', 'sort'])(data)
        }
      })
      console.log(data)
    })
    this.loading = true
    this.$api.goods.getCategoryList().then((r) => {
      this.loading = false
      console.log(r)
      this.cateTreeData = r.data.data.tree.children
      console.log(this.cateTreeData)
    })
  },
  methods: {
    onClose () {
      this.reset()
    },
    reset () {
      this.parentId = ''
      this.expandedKeys = []
      this.checkedKeys.checked.splice(0, this.checkedKeys.checked.length)
      this.form.resetFields()
      this.loading = false
    },
    handleCheck (checkedKeys) {
      console.log(checkedKeys)
      this.checkedKeys = checkedKeys
    },
    handleExpand (expandedKeys, info) {
      console.log(expandedKeys)
      console.log(info)
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    handleSubmit () {
      let checkedArr = Object.is(this.checkedKeys.checked, undefined) ? this.checkedKeys : this.checkedKeys.checked
      console.log(checkedArr)
      if (checkedArr.length > 1) {
        this.$message.error('最多只能选择一个上级分类，请修改')
        return
      }
      if (checkedArr[0] === this.id) {
        this.$message.error('不能选择自己作为上级分类，请修改')
        return
      }
      if (checkedArr.length) {
        for (let i = 0; i < this.childrenId.length; i++) {
          console.log(this.childrenId[i])
          console.log(this.id)
          if (this.id === this.childrenId[i]) {
            this.$message.error('不能选择子集作为上级分类，请修改')
            return
          }
        }
      }
      if (checkedArr.length === 0) {
        this.parentId = ''
      }
      this.parentId = checkedArr[0]
      this.form.validateFields((err, values) => {
        values.id = this.id
        values.parentId = this.parentId
        console.log(values)
        if (!err) {
          this.loading = true
          console.log(values)
          this.$api.goods.putCategory(values).then(() => {
            this.$emit('success')
            this.$message.success('修改类型成功')
            this.$router.push({path: `./view`})
            this.reset()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
